package com.hhs.storage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hhs.storage.bean.*;
import com.hhs.storage.dao.LeaderTaskDao;
import com.hhs.storage.service.BaseUserService;
import com.hhs.storage.service.LeaderTaskService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhs.storage.service.ProjectWorkFlowService;
import com.hhs.storage.service.TopicMessageService;
import com.hhs.storage.util.DateEasy;
import com.hhs.storage.util.StringUtil;
import com.hhs.storage.util.SysUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hhs
 * @since 2023-05-12
 */
@Service
@Transactional
public class LeaderTaskServiceImpl extends ServiceImpl<LeaderTaskDao, LeaderTask> implements LeaderTaskService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private BaseUserService baseUserService;
    @Resource
    private TopicMessageService topicMessageService;
    @Resource
    private ProjectWorkFlowService workFlowService;

    /**
     * 获取表格数据
     *
     * @param leaderTask
     * @param inputParam relateType 指定类型数据  leader=领导  user=下属
     * @return
     */
    @Override
    public Map<String, Object> getAll(LeaderTask leaderTask, InputParam inputParam) {
        String loginUserId = SysUtil.getLoginUserId(request);//当前用户
        QueryWrapper<LeaderTask> qw = new QueryWrapper<>();
        qw.eq(leaderTask.getReadFlag() != null, "read_flag", leaderTask.getReadFlag());
        qw.ge(leaderTask.getLeaderTaskStartDate() != null, "leader_task_start_date", leaderTask.getLeaderTaskStartDate());
        qw.le(leaderTask.getLeaderTaskEndDate() != null, "leader_task_end_date", leaderTask.getLeaderTaskEndDate());

        if (inputParam.getRelateType().equals("leader")) {
            //查询条件
            if (StringUtils.isNotEmpty(leaderTask.getLeaderId())) {
                //查询领导任务时，必须我是执行人
                qw.in("leader_id", leaderTask.getLeaderId().split(","));
            }
            if(StringUtil.iszNull(inputParam.getUserId())){
                qw.eq("user_id", loginUserId);
            }else{
                qw.eq("user_id", inputParam.getUserId());
            }
        } else if (inputParam.getRelateType().equals("user")) {
            if (StringUtils.isNotEmpty(leaderTask.getUserId())) {
                //查询下属任务，必须我是领导
                qw.in("user_id", leaderTask.getUserId().split(","));
            }
            if (StringUtils.isNotEmpty(leaderTask.getLeaderId())) {
                qw.eq("leader_id", leaderTask.getLeaderId());
            }else{
                qw.eq("leader_id", loginUserId);
            }
        }
        //加入查询条件 全员计划领导查看页面用
        if(!StringUtil.iszNull(leaderTask.getTitle())){
            qw.like("title",leaderTask.getTitle());
        }
        if(!StringUtil.iszNull(leaderTask.getContent())) {
            qw.like("content", leaderTask.getContent());
        }
        if(!StringUtil.iszNull(leaderTask.getStatus())) {
            qw.eq("status", leaderTask.getStatus());
        }
        if(inputParam.getLevels()!=null&&inputParam.getLevels().length!=0) {
            qw.in("level", Arrays.asList(inputParam.getLevels()));
        }
        if(!StringUtil.iszNull(leaderTask.getCreateTime())) {
            qw.ge("create_time", new DateEasy(leaderTask.getCreateTime()).toYYYYhMMhDDhHHcMMcSS());
        }
        if(!StringUtil.iszNull(leaderTask.getCompleteTime())) {
            qw.le("complete_time", new DateEasy(leaderTask.getCompleteTime()).toYYYYhMMhDDhHHcMMcSS());
        }
        //下属的姓名
        if(!StringUtil.iszNull(inputParam.getUserName())){
            qw.inSql("user_id","select id_ from base_user where name_ like '%"+inputParam.getUserName()+"%'");
        }
        //加入查询条件 全员计划领导查看页面用
        qw.orderByDesc("create_time");
        //分页查询
        Page<LeaderTask> result = this.page(new Page<LeaderTask>(
                inputParam.getPage(),
                inputParam.getSize()), qw);
        List<LeaderTask> list = result.getRecords();

        for (int i = 0; i < list.size(); i++) {
            LeaderTask task = list.get(i);
            task.setUser(baseUserService.getById(task.getUserId()));
            task.setLeader(baseUserService.getById(task.getLeaderId()));
        }
        long total = result.getTotal();
        //统计数目
        QueryWrapper<LeaderTask> q1=qw.clone();
        q1.eq("status",0);
        int nc=this.count(q1);
        QueryWrapper<LeaderTask> q2=qw.clone();
        q2.eq("status",1);
        int c=this.count(q2);
        Map<String,Object> data=new HashMap<>();
        data.put("notcomplete",nc);
        data.put("complete",c);
        Map map = new HashMap();
        map.put("code", 1);
        map.put("data",data);
        map.put("rows", list);
        map.put("total", total);
        return map;
    }

    /**
     * 新增编辑
     *
     * @param leaderTask 任务内容
     * @param memberIds  关联用户id
     * @param type       leader=领导  user=下属
     * @return
     */
    @Override
    public Map<String, Object> addOrUpdate(LeaderTask leaderTask, String memberIds, String type) {
        if (SysUtil.RELATE_TYPE_MAP.get(type) == null) {
            return ResponseInfo.error("错误参数");
        }
        if (StringUtils.isEmpty(leaderTask.getTitle())
                || StringUtils.isEmpty(leaderTask.getContent())
                || leaderTask.getLeaderTaskStartDate() == null
                || leaderTask.getLeaderTaskEndDate() == null) {
            return ResponseInfo.error("错误参数");
        }
        if (leaderTask.getId() == null) {
            return add(leaderTask, memberIds, type);
        } else {
            return edit(leaderTask, memberIds, type);
        }
    }

    /**
     * 新增
     *
     * @param leaderTask 任务内容
     * @param memberIds  关联用户id
     * @param type       leader=领导  user=下属
     * @return
     */
    public Map<String, Object> add(LeaderTask leaderTask, String memberIds, String type) {
        String loginUserId = SysUtil.getLoginUserId(request);//当前登录用户id
        if(!StringUtil.iszNull(leaderTask.getUserId())){
            loginUserId=leaderTask.getUserId();
        }
        leaderTask.setCreateTime(LocalDateTime.now());//设置当前时间
        leaderTask.setReadFlag(0);
        String[] userIds = memberIds.split(",");
        for (int i = 0; i < userIds.length; i++) {
            String userId = userIds[i];
            //发布领导任务
            if (type.equals("leader")) {
                leaderTask.setUserId(loginUserId);
                leaderTask.setLeaderId(userId);
            } else {
                //发布下属任务
                leaderTask.setLeaderId(loginUserId);
                leaderTask.setUserId(userId);
            }
            //如果是完成，设置完成时间
//            if (leaderTask.getStatus().equals(LeaderTask.STATE_COMPLETE)) {
//                leaderTask.setCompleteTime(LocalDateTime.now());
//            }
            leaderTask.setId(null);
            this.save(leaderTask);
//            workFlowService.addWorkFlow(leaderTask.getId() + "", leaderTask.getLeaderWk(), 2);
//            workFlowService.addWorkFlow(leaderTask.getId() + "", leaderTask.getSubWk(), 3);

        }
        return ResponseInfo.success("添加任务成功");
    }

    /**
     * 编辑
     *
     * @param leaderTask 任务内容
     * @param memberIds  关联用户id
     * @param type       leader=领导  user=下属
     * @return
     */
    public Map<String, Object> edit(LeaderTask leaderTask, String memberIds, String type) {
        UpdateWrapper uw = new UpdateWrapper<LeaderTask>();
        uw.set("title", leaderTask.getTitle());
        uw.set("content", leaderTask.getContent());
        uw.set("status", leaderTask.getStatus());
        uw.set("level", leaderTask.getLevel());
        uw.set("leader_task_start_date", leaderTask.getLeaderTaskStartDate());
        uw.set("leader_task_end_date", leaderTask.getLeaderTaskEndDate());
        uw.set("sub_content", leaderTask.getSubContent());
        uw.set("sub_progress", leaderTask.getSubProgress());
        uw.set("read_flag", leaderTask.getReadFlag());
        //进度条100%关联状态值
//        if(leaderTask.getSubProgress().equals(100)){
//            uw.set("status",LeaderTask.STATE_COMPLETE);
//            uw.set("complete_time", LocalDateTime.now());
//        }else{
//            uw.set("status",LeaderTask.STATE_UNCOMPLETED);
//            uw.set("complete_time", null);
//        }
        //状态值独立处理，不关联进度条
        if (leaderTask.getStatus().equals(LeaderTask.STATE_UNCOMPLETED)) {
            uw.set("complete_time", null);
        } else if (leaderTask.getStatus().equals(LeaderTask.STATE_COMPLETE)) {
            uw.set("complete_time", LocalDateTime.now());
        }
        uw.eq("id", leaderTask.getId());
        this.update(uw);
//        workFlowService.addWorkFlow(leaderTask.getId() + "", leaderTask.getLeaderWk(), 2);
//        workFlowService.addWorkFlow(leaderTask.getId() + "", leaderTask.getSubWk(), 3);

        return ResponseInfo.success("编辑任务成功");
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> dele(String id) {
        LeaderTask leaderTask = this.getById(id);
        if (leaderTask == null) {
            return ResponseInfo.error("错误的参数");
        }
        String userId = SysUtil.getLoginUserId(request);
        if (userId.equals(leaderTask.getLeaderId()) == false && userId.equals(leaderTask.getUserId()) == false) {
            return ResponseInfo.error("没有权限删除");
        }
        topicMessageService.deleteByTopicId(id);
        workFlowService.deleByPlanId(id);
        this.removeById(id);
        return ResponseInfo.success("删除成功");
    }

    /**
     * 修改状态
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public Map<String, Object> stateChange(Integer id, Integer status) {
        LeaderTask leaderTask = this.getById(id);
        if (leaderTask == null) {
            return ResponseInfo.error("错误的参数");
        }
        if (SysUtil.PLAN_STATE_MAP.get(status) == null) {
            return ResponseInfo.error("错误的参数");
        }
        if (leaderTask.getStatus().equals(status)) {
            return ResponseInfo.error("状态已改变");
        }
        UpdateWrapper<LeaderTask> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.set("status", status);
        String completeTime = null;
        if (status.equals(LeaderTask.STATE_UNCOMPLETED)) {
            updateWrapper.set("complete_time", null);
        } else if (status.equals(LeaderTask.STATE_COMPLETE)) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            String localDateTimeNowStr = localDateTimeNow.format(formatter);
            completeTime = localDateTimeNowStr;
            updateWrapper.set("complete_time", LocalDateTime.now());
        }
        this.update(updateWrapper);
        return ResponseInfo.success(completeTime);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> detail(Integer id) {
        LeaderTask task = this.getById(id);
        task.setUser(baseUserService.getById(task.getUserId()));
        task.setLeader(baseUserService.getById(task.getLeaderId()));
        //查询工序
        QueryWrapper qw2 = new QueryWrapper<ProjectWorkFlow>();
        qw2.eq("project_plan_id", id);
        qw2.eq("type", 2);
        qw2.orderByAsc("step");
        List<ProjectWorkFlow> projectWorkFlowList = workFlowService.list(qw2);
        task.setLeaderWk(projectWorkFlowList);
        QueryWrapper qw3 = new QueryWrapper<ProjectWorkFlow>();
        qw3.eq("project_plan_id", id);
        qw3.eq("type", 3);
        qw3.orderByAsc("step");
        projectWorkFlowList = workFlowService.list(qw3);
        task.setSubWk(projectWorkFlowList);

        //设置为已读
        String userId = SysUtil.getLoginUserId(request);
        if (task.getUserId().equals(userId) && (task.getReadFlag() == null || task.getReadFlag().equals(0))) {
            UpdateWrapper uw = new UpdateWrapper<LeaderTask>();
            LocalDateTime readTime = LocalDateTime.now();
            task.setReadTime(readTime);
            uw.set("read_time", readTime);
            uw.set("read_flag", 1);
            uw.eq("id", task.getId());
            this.update(uw);
        }
        return ResponseInfo.success(task);
    }

    /**
     * 获取任务相关人员信息
     *
     * @param type leader=查询领导  user=查询下属
     * @return
     */
    @Override
    public Map<String, Object> relatePersonalList(String type) {
        String userId = SysUtil.getLoginUserId(request);
        if (SysUtil.RELATE_TYPE_MAP.get(type) == null) {
            return ResponseInfo.error("错误参数");
        }
        List<BaseUser> list = this.baseMapper.relatePersonalList(type, userId);
        return ResponseInfo.success(list);
    }

    @Override
    public Map<String, Object> remind() {
        String userId = SysUtil.getLoginUserId(request);
        QueryWrapper qw2 = new QueryWrapper<LeaderTask>();
        qw2.eq("user_id", userId);
        qw2.eq("read_flag", 0);
        List list = this.list(qw2);
        return ResponseInfo.success(list.size());
    }
}
